#!/usr/bin/env perl
# Perl script for generating random matrix

# Usage:
#./gen_matrix.pl [number_of_rows number_of_columns max_number 0(int)_or_float] [-o output_file]

# Display the duration of the matrix generation

# Basile Clout, September 2007

use Time::HiRes qw(gettimeofday tv_interval);

use Getopt::Long;

use strict;			# Always declare variables with my (local scope)
use warnings;

my $max = 1000;			# Max range of generated random numbers
my $rows = 10;			# Number of rows
my $cols = 10;			# Number of columns
my $float = 1;			# if float==0, int are generated, else, float
my $out;

GetOptions("o=s"=>\$out);	# Get opt -o to get the output handle
($out) ? open(OUT, ">$out") : open(OUT, ">-"); # output is standard output if no $out defined, $out else

($#ARGV>-1) ? $rows = 10 : $rows = $ARGV[0]; # If arg on the command line ...
($#ARGV>0) ? $cols = 10 : $cols = $ARGV[1];
($#ARGV>1) ? $max = 1000 : $max = $ARGV[2];
($#ARGV>2) ? $float = 1 : $float = $ARGV[3];

print OUT $rows." ".$cols." ".$max." ".$float."\n"; # First line: number of rows, number of columns, #max number, format(int or float)


my $t0 = [gettimeofday];
for (my $i=0;$i<$rows;$i++){	# Not a memory hog if $rows very big
				# (compatively to (1..$rows)
  for (my $j=0;$j<$cols;$j++){
    (!$float==0) ? print OUT sprintf("%.3f ", rand($max)) : print OUT sprintf("%d ", int(rand($max)));
  }

  print OUT "\n";
}

my $elapsed = tv_interval ($t0);
print "Matrix generated in (including IOs): ${elapsed}s.\n";
